
//
//  ZWPlayMusicTool.m
//  08.音乐播放器
//
//  Created by mac on 16/3/14.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "ZWPlayMusicTool.h"
#import <AVFoundation/AVFoundation.h>

@interface ZWPlayMusicTool()<AVAudioPlayerDelegate>
//播放音乐的对象
@property (strong,nonatomic) AVAudioPlayer  *player;
//保存歌曲文件名
@property (strong,nonatomic) NSString *oldFileName;
//临时接收block
@property (strong,nonatomic) void (^complete)();

@end

@implementation ZWPlayMusicTool

+ (ZWPlayMusicTool *)sharedPlayMusic{

    static ZWPlayMusicTool *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instance = [[ZWPlayMusicTool alloc]init];
    });
    return _instance;
}

//播放歌曲的方法
- (void)playMusicWithFileName:(NSString *)fileName andDidComplete:(void(^)())complete{

    //通过判断,解决暂停后,再次点击播放按钮,歌曲从头播放的bug
    if (![self.oldFileName isEqualToString:fileName]) {
        self.oldFileName = fileName;
        NSError *error = nil;
        //创建播放对象并实例化
        self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:fileName withExtension:nil] error:&error];
        if (error) {
            NSLog(@"播放歌曲的方法出错,error:%@",error);
        }
        //准备播放
        [self.player prepareToPlay];
    }
    self.complete = complete;
    self.player.delegate = self;
    
    //播放
    [self.player play];
    
}

#pragma mark - player的代理方法(播放结束后)
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    self.complete();
}

//暂停播放
- (void)pause{

    [self.player pause];
}

//currentTime的getter方法
- (NSTimeInterval )currentTime{

    return self.player.currentTime;
}
//duration的getter方法
- (NSTimeInterval )duration{

    return self.player.duration;
}
//currentTime的setter方法
- (void)setCurrentTime:(NSTimeInterval)currentTime{

    self.player.currentTime = currentTime;
}

@end
